/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.perftests;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicInteger;

import org.latestbit.smartobjects.*;
import org.latestbit.smartobjects.exceptions.SmartBusSystemException;
import org.latestbit.smartobjects.network.EndpointLocation;
import org.latestbit.smartobjects.network.IHandshakeManager;
import org.latestbit.smartobjects.network.IHandshakeManagerListener;
import org.latestbit.smartobjects.testmodel.*;

public class SimpleClient implements Runnable {
	ISmartBus bus = new SmartBus();
	static String location = "tcp://localhost:7777";
	SimpleInterface clientStub = new SimpleInterface (); 
	AtomicInteger sendTps = new AtomicInteger(0);
	AtomicInteger rcvdTps = new AtomicInteger(0);
	volatile boolean stopThreadFlag = false;
	static boolean syncMode = false;
	static int syncThreadsCnt = 1;
		
	public static void main(String[] args) throws Exception {
		if(args.length > 0)
			location = args[0];
		if(args.length > 1)
			syncMode = true;
		if(args.length > 2 && syncMode)
			syncThreadsCnt = Integer.valueOf(args[2]);		
		new SimpleClient().start();
		System.out.println("Exiting...");
	}

	private void start() throws Exception {
		bus.getHandshakeManagerFactory().setHandshakeManagerListener(new IHandshakeManagerListener() {

			@Override
			public void onHandshakeBegin(IHandshakeManager manager) {
				System.out.println("Handshake begin...");
			}

			@Override
			public void onHandshakeComplete(IHandshakeManager manager) {
				System.out.println("Handshake complete.");	
			}

			@Override
			public void onHandshakeError(IHandshakeManager manager, Exception ex) {
				System.err.println("Handshake error: "+ex);
			}
			
		});
		BufferedReader input = new BufferedReader ( new InputStreamReader ( System.in ) );
		
		System.out.println("SimpleClient is loading...");
		
		if(syncMode)
			System.out.println("Sync mode activated! Threads: " + syncThreadsCnt);
		
		clientStub.resolve( bus, new EndpointLocation ( bus, location) );
		Thread calcThread = new Thread(this);
		System.out.println("SimpleClient starting perfomance load to server. Please enter to exit");
		calcThread.start();

		Thread loadThread = null;
		if(!syncMode) {
			loadThread = new Thread(this.new LoadTest());
			loadThread.start();			
		}
		else {
			for(int i=0; i < syncThreadsCnt; i++) {
				new Thread(this.new LoadTest()).start();
			}
		}
		
		input.readLine();
		System.out.println("SimpleClient is unloading...");
		stopThreadFlag = true;
		calcThread.join();
		if(loadThread!=null)
			loadThread.join();
		clientStub.destroy();
		bus.destroy();
	}
	

	@Override
	public void run() {
		while(!stopThreadFlag) {
			try {
				Thread.sleep(1000);
				System.err.print("Send TPS: "+sendTps.getAndSet(0)+". ");
				System.err.println("Receive TPS: "+rcvdTps.getAndSet(0));
			} catch (InterruptedException e) {
				e.printStackTrace();
				break;
			}
		}
	}
	
	class LoadTest implements Runnable, ISimpleInterfaceCallback {

		@Override
		public void run() {
			while(!stopThreadFlag) {				
				try {
					if(!syncMode) {
						clientStub.helloWorldRequest("World", this, null );
					}
					else {
						clientStub.helloWorld("World");
					}
				} catch (Exception e) {
					e.printStackTrace();
					break;
				}
				int sTpsVal = sendTps.incrementAndGet();
				if(syncMode) {
					rcvdTps.set(sTpsVal);
				}
			}
		}
		
		@Override
		public void onHelloWorldResponse(String value, Object userObject) {
			rcvdTps.incrementAndGet();
		}

		@Override
		public void onHelloWorld2Response(String value, Object userObject) {}

		@Override
		public void onHelloWorld3Response(ISimpleStructure value, Object userObject) {}

		@Override
		public void onHelloWorld4Response(String value, Object userObject) {}

		@Override
		public void onHelloWorld4Response(SimpleException ex, Object userObject) {}

		@Override
		public void onManualDestroyResponse(Object userObject) {}

		@Override
		public void onResponseSystemException(String operationId,
				SmartBusSystemException ex, Object userObject) {}

		@Override
		public void onResponseTimeout(String operationId, Object userObject) {}

		@Override
		public void onHelloWorldEncryptedResponse(String value, Object userObject) {}

		
	}

}
